import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormRadio } from '@ant-design/pro-form';
import { save, update, checkClassName, checkRule } from '@/services/system/task';
import {SystemDictSelect} from '@/components/system/dict'

const SystemTaskForm = (props) => {
  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建任务成功!');
    else message.error('新建任务失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改任务成功!');
    else message.error('修改任务失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue };

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  const validatorRule = (rule, value, callback) => {
    if (value) {
      checkRule(value).then((result) => {
        if (result.success) {
          callback();
        } else {
          callback("定时任务规则不正确!");
        }
      });
    } else {
      callback();
    }
  }

  const validatorClassName = (rule, value, callback) => {
    if (value) {
      checkClassName({ id: values.id, className: value}).then((result) => {
        if (result.success) {
          callback();
        } else {
          callback("任务类名不存在，或已被使用!");
        }
      });
    } else {
      callback();
    }
  }

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改任务信息' : '新增任务信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={values} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <Form.Item label="任务分组" name="group" rules={[{ required: true, message: '请选择任务分组!' }]}>
          <SystemDictSelect parentValue="system_task_group"/>
        </Form.Item>
        <ProFormText  name="name" label="任务名称" rules={[{ required: true, message: '请输入任务名称!'}, {max: 20, message: '任务名称过长!'}]}/>
        <ProFormText  name="rule" label="执行规则" rules={[{ required: true, message: '请输入执行规则!'}, {validator: validatorRule}]}/>
        <ProFormText  name="className" label="任务类名" rules={[{ required: true, message: '请输入任务类名!'}, {validator: validatorClassName}]}/>
        <ProFormRadio.Group  
          name="usedStatus" label="启用状态" 
          options={[
            { value: 'YES', label: '启用', },
            { value: 'NO', label: '停用', },
          ]}
          initialValue="YES"
          rules={[{ required: true, message: '请选择启用状态!' }]}
        />
      </ProForm>
    </Modal>
  );
};

export default SystemTaskForm;